<?php

namespace common\modules\zt\controllers\frontend;

use common\helpers\Http;
use common\modules\zt\models\beierban\frontend\Item;
use common\modules\zt\Module;
use Yii;
use yii\helpers\ArrayHelper;
use yii\web\Controller;

class BeierbanController extends Controller
{

    /**
     * @var array 描述内容
     */
    public $physicalMapping = [];

    /**
     * @var string 投票入口地址
     */
    public $voteEntryUrl = '';

    public $wxUserGroupSyncUrl = '';

    /**
     * @inheritdoc
     */
    public function init()
    {
        parent::init();
        $this->physicalMapping = Module::current()->beierbanPhysicalMapping;
        $this->voteEntryUrl = Module::current()->voteEntryUrl;
        $this->wxUserGroupSyncUrl = Module::current()->wxUserGroupSyncUrl;
    }

    /**
     * @param array $items
     * @return array
     */
    protected function analyseItems($items)
    {
        foreach ($this->physicalMapping as $key => $config)
        {
            if (isset($items[$key]) && is_array($items[$key]))
            {
                $itemSum = array_sum($items[$key]);
                $itemCount = count($items[$key]);
                $config['score1'] = $itemSum;
                $config['score2'] = round(($itemSum - $itemCount) / ($itemCount * 4) * 100);
                $config['score2'] = max($config['score2'], 0);
            }

            $this->physicalMapping[$key] = $config;
        }

        $result = [];
        // 偏颇体质key数组
        $biasedKeyArray = [2, 3, 4, 5, 6, 7, 8, 9];

        // 计算最高的偏颇体质
        $biasedMatchKey = 0;
        $biasedMaxValue = 0;
        foreach ($biasedKeyArray as $key)
        {
            $biasedMaxValue = max($biasedMaxValue, $this->physicalMapping[$key]['score2']);
            if ($biasedMaxValue == $this->physicalMapping[$key]['score2'])
            {
                $biasedMatchKey = $key;
            }
        }

        // 1. 偏颇体质最高值>=40，则输出最大分值的偏颇体质。
        if ($biasedMaxValue >= 40 && $biasedMatchKey)
        {
            $result[] = [
                'title' => '您是' . $this->physicalMapping[$biasedMatchKey]['name'],
                'desc' => $this->physicalMapping[$biasedMatchKey]['desc'],
                'groupId' => $this->physicalMapping[$biasedMatchKey]['wxGroupId'],
                'no' => $this->physicalMapping[$biasedMatchKey]['no'],
            ];
            return $result;
        }

        if ($biasedMaxValue < 30)
        {
            // 2. 偏颇质都小于30分，而且平和质>60，就输出平和质。
            if ($this->physicalMapping[1]['score2'] >= 60)
            {
                $result[] = [
                    'title' => '您是平和体质',
                    'desc' => $this->physicalMapping[1]['desc'],
                    'groupId' => $this->physicalMapping[1]['wxGroupId'],
                    'no' => $this->physicalMapping[1]['no'],
                ];
                return $result;
            }
            // 3. 偏颇质都小于30分，而且平和质<60，就输出得分最高项。
            if ($this->physicalMapping[1]['score2'] < 60)
            {
                if ($this->physicalMapping[1]['score2'] >= $biasedMaxValue)
                {
                    $result[] = [
                        'title' => '您是平和体质',
                        'desc' => $this->physicalMapping[1]['desc'],
                        'groupId' => $this->physicalMapping[1]['wxGroupId'],
                        'no' => $this->physicalMapping[1]['no'],
                    ];
                }
                else
                {
                    $result[] = [
                        'title' => '您是' . $this->physicalMapping[$biasedMatchKey]['name'],
                        'desc' => $this->physicalMapping[$biasedMatchKey]['desc'],
                        'groupId' => $this->physicalMapping[$biasedMatchKey]['wxGroupId'],
                        'no' => $this->physicalMapping[$biasedMatchKey]['no'],
                    ];
                }
                return $result;
            }
        }

        // 此时, 可以确定:偏颇体质都小于40分但存在大于30的＋

        if ($this->physicalMapping[1]['score2'] >= 60)
        {
            // 偏颇体质都小于40分但存在大于30的＋，并且平和质>60分，就输出“基本是平和质”+“倾向于是最大分值的偏颇体质”。
            $result[] = [
                'title' => '您基本是平和体质, 倾向于' . $this->physicalMapping[$biasedMatchKey]['name'],
                'desc' => $this->physicalMapping[1]['desc'],
            ];
            $result[] = [
                'title' => $this->physicalMapping[$biasedMatchKey]['name'],
                'desc' => $this->physicalMapping[$biasedMatchKey]['desc'],
                'groupId' => $this->physicalMapping[$biasedMatchKey]['wxBiasedGroupId'],
                'no' => $this->physicalMapping[$biasedMatchKey]['biasedNo'],
            ];
        }
        else
        {
            // 偏颇体质都小于40分但存在大于30的＋，平和质<60分，就输出“倾向于是最大分值的偏颇体质”。
            $result[] = [
                'title' => '您倾向于' . $this->physicalMapping[$biasedMatchKey]['name'],
                'desc' => $this->physicalMapping[$biasedMatchKey]['desc'],
                'groupId' => $this->physicalMapping[$biasedMatchKey]['wxBiasedGroupId'],
                'no' => $this->physicalMapping[$biasedMatchKey]['biasedNo'],
            ];
        }

        return $result;
    }

    /**
     * 解析投票结果
     */
    public function actionVote()
    {
        $openid = Yii::$app->request->get('openid');
        if ( ! $openid)
        {
            Yii::warning("找不到OpenID,直接跳转到投票页:" . $this->voteEntryUrl, __METHOD__);
            return $this->redirect($this->voteEntryUrl);
        }

        $model = Item::find()
            ->where([
                'openid' => $openid,
            ])
            ->one();
        if ( ! $model)
        {
            $model = new Item;
            $model->openid = $openid;
        }

        $model->save_id = Yii::$app->request->get('save');

        $items = (array) Yii::$app->request->get('item');
        $model->items = json_encode($items);

        if ( ! $model->save(false))
        {
            Yii::warning('保存分析记录失败:' . $model->formatErrors(), __METHOD__);
        }

        $result = $this->analyseItems($items);

        if ($openid)
        {
            $groupId = false;
            foreach ($result as $row)
            {
                $current = ArrayHelper::getValue($row, 'groupId');
                if ($current)
                {
                    $groupId = $current;
                    break;
                }
            }

            if ($groupId)
            {
                $url = str_replace(['[openid]', '[group_id]'], [$openid, $groupId], $this->wxUserGroupSyncUrl);
                $response = Http::get($url);
                Yii::trace("请求[{$url}], 并获取结果:" . $response->body, __METHOD__);
            }
            else
            {
                Yii::warning("找不到微信用户组", __METHOD__);
            }
        }
        else
        {
            Yii::warning("找不到OpenID", __METHOD__);
        }

        return $this->renderPartial('vote', [
            'result' => $result
        ]);
    }

    /**
     * 查看投票结果
     *
     * @return string|\yii\web\Response
     */
    public function actionVoteResult()
    {
        $openid = Yii::$app->request->get('openid');
        if ( ! $openid)
        {
            Yii::warning("找不到OpenID,直接跳转到投票页:" . $this->voteEntryUrl, __METHOD__);
            return $this->redirect($this->voteEntryUrl);
        }

        /** @var Item $model */
        $model = Item::find()
            ->where([
                'openid' => $openid,
            ])
            ->one();
        if ( ! $model)
        {
            Yii::warning("当前用户没有投票记录,引导他去投票:" . $this->voteEntryUrl, __METHOD__);
            return $this->redirect($this->voteEntryUrl);
        }

        $result = $this->analyseItems(json_decode($model->items, true));

        return $this->renderPartial('vote', [
            'result' => $result
        ]);
    }
}
